<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/11/16
 * Time: 上午10:37
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BannerController extends Controller
{
    public function index()
    {
        return view('main::banner', \Request::all());
    }

    public function all()
    {
        $data['items'] = Banner::with('image')->orderBy('list_order', 'asc')->get();
        return success($data);
    }


    public function store(Request $request)
    {
        try {
            $data = $request->only('image_id', 'redirect_to', 'list_order');
            $validator = Validator::make($request->all(), [
                'image_id' => 'required',
                'redirect_to' => 'required'
            ]);
            if ($validator->fails()) {
                return fail(400, $validator->errors()->first());
            }
            Banner::create([
                'image_id' => $data['image_id'],
                'redirect_to' => $data['redirect_to'],
                'list_order' => isset($data['list_order']) ? $data['list_order'] : 1
            ]);

            return success();
        } catch (\Exception $e) {
            Log::error($e);
            return fail(400, '添加失败');
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $banner = Banner::find($id);
            $image_id = $request->input('image_id');
            $redirect_to = $request->input('redirect_to');
            $list_order = $request->input('list_order');
            $validator = Validator::make($request->all(), [
                'image_id' => 'required',
                'redirect_to' => 'required'
            ]);
            if ($validator->fails()) {
                return fail(400, $validator->errors()->first());
            }
            if ($image_id) {
                $banner->image_id = $image_id;
            }
            if ($redirect_to) {
                $banner->redirect_to = $redirect_to;
            }
            if ($list_order) {
                $banner->list_order = $list_order;
            }
            $banner->save();
            return success();
        } catch (\Exception $e) {
            Log::error($e);
            return fail(400, '添加失败');
        }
    }

    public function destroy($id)
    {
        try {
            $banner = Banner::find($id);
            $banner->delete();

            return success();
        } catch (\Exception $e) {
            Log::error($e);
            return fail(400, '删除失败');
        }
    }
}